package com.njupt.common.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;

import com.njupt.blog.Constants;
import com.njupt.service.UniversalManager;
import com.njupt.user.model.UploadFile;
import com.njupt.user.model.User;

@ParentPackage(value = "user")
@Namespace(value = "")
public class FileAction {
	private UniversalManager manager;
	public String execute() {
		return "";
	}
	
	public void changeAvatar(){
		Long fileId =Long.parseLong(ServletActionContext.getRequest().getParameter("fileId")+""); 
		User currentUser = (User) ServletActionContext.getRequest().getSession().getAttribute(Constants.SECURITY_CONTEXT_KEY);
		currentUser.setPictureAppended(fileId);
		manager.save(currentUser);
	}
	
	public void uploadFile() throws ServletException, IOException {
		String status = "";     
		String serverRealPath = "";
		Long fileId = 0l;
		HttpServletResponse  response = ServletActionContext.getResponse();
		HttpServletRequest  request = ServletActionContext.getRequest();
		String  saveDirectory = "D:\\njupt\\blog\\";
		File mir = new File(saveDirectory);
		if(!mir.exists())  mir.mkdir();
		try {
			DiskFileItemFactory dtf = new DiskFileItemFactory();  //磁盘对象
			ServletFileUpload upload = new ServletFileUpload(dtf);//声明解析request的对象
			List<FileItem> items = upload.parseRequest(request);
			for (FileItem item : items) {
					String fileName = item.getName();
					InputStream content = item.getInputStream();
					String tempName = System.currentTimeMillis() + ".blog.file";
					
					UploadFile  upf = new UploadFile();
					upf.setFileName(fileName);
					upf.setSaveFileName(tempName);
					int count = fileName.lastIndexOf(".");
				    String postfix = fileName.substring(count+1).toLowerCase();
				    postfix = postfix.toLowerCase();
				    if( postfix == "jpg" || postfix == "gif" || postfix == "gif" || postfix == "bmp")
				    	upf.setType(1l);
				    else if(postfix == "mp3" || postfix == "wma" )
				    	upf.setType(2l);
				    else if(postfix == "mp4" || postfix == "rmvb" || postfix == "flv" )
				    	upf.setType(3l);
				    else
				    	upf.setType(4l);
				    
				    upf.setPostfix(postfix);
				    
				    
					upf.setUploadTime(new Date());
					User currentUser =  (User) ServletActionContext.getRequest().getSession().getAttribute(Constants.SECURITY_CONTEXT_KEY);
					upf.setUserId(currentUser.getId());
					upf.setFileLength(item.getSize());
					
					File f = new File(saveDirectory+tempName);
					FileUtils.copyInputStreamToFile(content, f);
					content.close();
					upf = (UploadFile) manager.save(upf);
					
					status = "upload Success!";
					serverRealPath = f.getAbsolutePath();
					fileId = upf.getId();
			}
		} catch (FileUploadException e) {
		  throw new ServletException("Parsing file upload failed.", e);
	  }
		response.setContentType("text/html");
		response.setCharacterEncoding("UTF-8");
		response.getWriter().print("{status:'"+status+"',path:'"+serverRealPath+"',fileId:"+fileId+"}");
	}
	
	
	 public void previewPic() throws IOException{   
	    	Long fileId =Long.parseLong(ServletActionContext.getRequest().getParameter("fileId")+"");    
	    	UploadFile upf = (UploadFile)manager.get(UploadFile.class,fileId);
	    	
	    	String saveFileName = upf.getSaveFileName();
	    	FileInputStream in = new FileInputStream("D:\\njupt\\blog\\"+saveFileName);
	    	byte[] bytes = new byte[1024];
	    	int m = 0;
	    	ServletActionContext.getResponse().setContentType("image/jpeg");
	    	OutputStream outx = ServletActionContext.getResponse().getOutputStream();
	    	while((m=in.read(bytes))!=-1){
	    		outx.write(bytes, 0, m);
	    	}
	    	in.close();
	    }
	    

	public UniversalManager getManager() {
		return manager;
	}
	public void setManager(UniversalManager manager) {
		this.manager = manager;
	}

	


}
	
